package cn.chi.org.service.impl;


import cn.chi.org.domain.Department;
import cn.chi.org.domain.Employee;
import cn.chi.org.mapper.EmployeeMapper;
import cn.chi.org.query.EmployeeQuery;
import cn.chi.org.service.IEmployeeService;
import cn.chi.user.domain.LoginInfo;
import cn.chi.user.mapper.LoginInfoMapper;
import cn.chi.util.MD5Utils;
import cn.chi.util.PageInfo;
import cn.chi.util.PageList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    /**
     * 查询全部数据
     * @return
     */
    @Override
    public List<Employee> queryAll() {
        return employeeMapper.loadAll();
    }

    @Override
    public PageList<Employee> queryPage(EmployeeQuery employeeQuery) {
        //1.查询总条数
        Long total = employeeMapper.queryCount(employeeQuery);
        //查询当前页数据
        List<Employee> rows = employeeMapper.queryData(employeeQuery);
        return new PageList<Employee>(total,rows);
    }

    @Override
    public void remove(Long id) {
        employeeMapper.delete(id);

    }

    @Override
    public Employee queryById(Long id) {
        return employeeMapper.loadById(id);
    }

    @Override
    public void addOrUpdate(Employee employee) {
        if (employee.getId() == null){
            System.out.println(employee);
            //获取用户输入的密码
            String password = employee.getPassword();
            String salt = UUID.randomUUID().toString();
            String md5 = MD5Utils.encrypByMd5(password + salt);
            employee.setPassword(md5);
            employee.setSalt(salt);
            employeeMapper.save(employee);
            Employee empDB = employeeMapper.loadByUserName(employee.getUsername());
            LoginInfo logIninfo =employee2LogIninfo(empDB);
            System.out.println(logIninfo);
            loginInfoMapper.save(logIninfo);
            employee.setLogininfo_id(logIninfo.getId());
            employeeMapper.update(employee);
        }else {
            employeeMapper.update(employee);
        }
    }

    private LoginInfo employee2LogIninfo(Employee employee) {
       LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee, loginInfo);
        loginInfo.setDisable(1);
        loginInfo.setType(0);
        return loginInfo;
    }

    @Override
    public void batchRemove(List<Long> ids) {
        employeeMapper.batchRemove(ids);
    }


}
